package com.itheima.wechat;

import cn.hutool.core.lang.UUID;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    JedisUtil jedisUtil;

    @Reference
    MemberService memberService;

    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletRequest request){
        String telephone = (String)map.get("telephone");
        String validateCode = (String)map.get("validateCode");
        //校验验证码
        String redisCode = jedisUtil.get(telephone + "002");
        if(null == redisCode || !redisCode.equals(validateCode)){
            return Result.error("验证码错误");
        }
        //查询当前手机号码是不是会员
        Member member = memberService.findByTelephone(telephone);
        //不是就注册
        if(null == member){
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            member = memberService.add(member);
        }
        //把用户信息存入session 或者cookie
//        request.getSession().setAttribute("userInfo",member);

        //把用户信息存入redis
        String token = UUID.randomUUID().toString();
        jedisUtil.add(token,60 * 60 * 24 * 15, JSON.toJSONString(member));
        return Result.success("",token);
    }


}
